package com.android.lovely.ui.viewmodel

import android.app.Activity
import androidx.lifecycle.viewModelScope
import com.android.lovely.R
import com.android.lovely.api.service.systemService
import com.android.lovely.data.PayData
import com.android.lovely.data.PayDetail
import com.android.lovely.framework.BaseViewModel
import com.android.lovely.framework.UIController.showToast
import com.android.lovely.framework.launchWithLoading
import com.android.lovely.user.UserManager
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import io.glassfy.androidsdk.GooglePlayManager
import io.glassfy.androidsdk.model.PurchaseParams
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow

/**
 *
 * @author why
 * @date 2025/3/25 19:17
 */
class PayViewModel: BaseViewModel() {

    private val _productFlow = MutableSharedFlow<PayData>(extraBufferCapacity = 1)
    val productFlow: SharedFlow<PayData> get() = _productFlow

    fun requestProductList() {
        viewModelScope.launchWithLoading {
            val products: PayData = systemService.getPayList()
            _productFlow.emit(products)
        }
    }

    fun pay(context: Activity, gem: PayDetail) {
        viewModelScope.launchWithLoading {
            val result = GooglePlayManager.purchase(
                context,
                gem.appleId,
                PurchaseParams(
                    UserManager.userInfo?.id?.toString() ?: return@launchWithLoading,
                    gem.price.toFloat()
                )
            )
            if (!result) {
                showToast(context.getString(R.string.pay_failed))
            }
        }
    }

    fun pay(context: Activity, gem: PayDetail, onNext: () -> Unit) {
        viewModelScope.launchWithLoading {
            val result = GooglePlayManager.purchase(
                context,
                gem.appleId,
                PurchaseParams(
                    UserManager.userInfo?.id?.toString() ?: return@launchWithLoading,
                    gem.price.toFloat()
                )
            )
            if (!result) {
                showToast(context.getString(R.string.pay_failed))
            }
        }.onComplete {
            onNext.invoke()
        }
    }
}